package com.zjj.concurrent.completableFuture;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @author zhanglei.zjj
 * @description 使用ThenCompose做结果转换，将上一阶段的CompletableFuture操作的结果拿到作为下一阶段的入参，并开启一个新的CompletableFuture
 * @date 2023/6/4 11:22
 */
public class ThenComposeTest {
    public static void main(String[] args) {
        CompletableFuture<Integer> future = CompletableFuture
                .supplyAsync(new Supplier<Integer>() {
                    @Override
                    public Integer get() {
                        int number = new Random().nextInt(30);
                        throw new RuntimeException("hhh");
//                        System.out.println("第一阶段：" + number);
//                        return number;
                    }
                })
                .thenCompose(new Function<Integer, CompletionStage<Integer>>() {
                    @Override
                    public CompletionStage<Integer> apply(Integer param) {
                        return CompletableFuture.supplyAsync(new Supplier<Integer>() {
                            @Override
                            public Integer get() {
                                int number = param * 2;
                                System.out.println("第二阶段：" + number);
                                return number;
                            }
                        });
                    }
                });
        Integer result = null;
        try {
            result = future.join();
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }

        /*CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "Hello");

        CompletableFuture<String> result1 = future2.thenApply(param -> param + " World");
        CompletableFuture<String> result2 = future2
                .thenCompose(param -> CompletableFuture.supplyAsync(() -> param + " World"));

        try {
            System.out.println(result1.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }*/
    }
}
